﻿using SqlSugar;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Shapes;
using WebFirst.Entities;
using WpfApp3.Services;

namespace WpfApp3.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {
        private readonly ILoginService _loginService;

        #region 实现IDialogAware接口
        DialogCloseListener IDialogAware.RequestClose => throw new NotImplementedException();

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {

        }

        public void OnDialogOpened(IDialogParameters parameters)
        {

        }
        #endregion

        #region 动态属性：用户名+密码
        private string userName;
        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged(); }
        }

        private string passWord;
        public string PassWord
        {
            get { return passWord; }
            set { passWord = value; RaisePropertyChanged(); }
        }
        #endregion

        public DelegateCommand<string> ExecuteCommand { get; private set; }

        #region 构造函数
        public LoginViewModel(ILoginService loginService)
        {
            _loginService = loginService;
            ExecuteCommand = new DelegateCommand<string>(Execute);
        }
        #endregion

        private void Execute(string obj)
        {
            switch (obj)
            {
                case "Login": Login(); break;
                    //case "LoginOut": LoginOut(); break;
                    //case "Resgiter": Resgiter(); break;
                    //case "ResgiterPage": SelectIndex = 1; break;
                    //case "Return": SelectIndex = 0; break;
            }
        }

        public async void Login()
        {
            //这段代码是一个基本的输入验证逻辑，主要功能是检查用户名和密码是否为空或仅包含空白字符。
            //如果任一字段为空，则直接返回而不执行后续操作。
            if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(PassWord))
            {
                MessageBox.Show("用户名和密码不能为空！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            // 数据库验证
            var loginResult = SqlSugarHelper.Db.Queryable<User>().Where(u => u.UserName == UserName && u.PassWord ==PassWord).First();

            if (loginResult != null)
            {
                //MessageBox.Show("登录成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                // 跳转到主窗体
                // 显示主窗口
                _loginService.ShowMainWindow();
                // 关闭登录窗口
                _loginService.CloseLoginWindow();
            }
            else
            {
                MessageBox.Show("用户名或密码错误！", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                //RefreshCheckCode();
            }
        }
    }
}
